package com.ioudi.digu.dao.support;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Query;

import com.ioudi.digu.util.ArrayUtil;

public class AbstractQuerySupport implements IQuerySupport
{

	private String[] filters;
	

	public Query createQuery(Query query, List<String> keys, Map<String, Object> condition)
	{
		String key;
    	if(keys == null)
    	{
    		return query;
    	}
    	int keyIndex = keys.size() - 1;
		while(keyIndex >= 0)
		{
			key = keys.get(keyIndex);
			createQueryItem(query, key, keyIndex, condition.get(key));
			keyIndex --;
		}
		return query;
	}
	
	protected void createQueryItem(Query query, String key, int index, Object value)
	{
		
	}

	public String createStatement(String voName, Map<String, Object> condition,
			List<String> keys)
	{
		String key;
		String sql = "";
		if(condition != null)
		{
			Set keySet = condition.keySet();
			Iterator iteraotr = keySet.iterator();
			Object value;
			boolean first = true;
			while(iteraotr.hasNext())
			{
				key = String.valueOf(iteraotr.next());
				if(filters != null && ArrayUtil.indexOf(filters, key) < 0)
				{
					continue;
				}
				sql += (first ? "" : " and ") + voName + "." + getStatementItemField(key)
				    + getStatementItemOperator(key, condition.get(key)) + 
				    (isValueSetInStatement(key) ? "" : "?");
				keys.add(key);
				first = false;		
			}		
		}
		return sql;
	}
	
	protected String getStatementItemField(String key)
	{
		return key;
	}
	
	protected String getStatementItemOperator(String key, Object value)
	{
		return "=";
	}
	
	protected boolean isValueSetInStatement(String key)
	{
		return false;
	}
	
	public String[] getFilters()
	{
		return filters;
	}

	public void setFilters(String[] filters)
	{
		this.filters = filters;
	}

}
